package com.platform.service.impl;

import com.github.pagehelper.PageInfo;
import com.platform.annotation.SysLog;
import com.platform.base.BaseService;
import com.platform.common.Const;
import com.platform.common.ServerResponse;
import com.platform.pojo.BigField;
import com.platform.pojo.Consumables;
import com.platform.pojo.User;
import com.platform.service.IConsumablesService;
import com.platform.service.ISolrSearchService;
import com.platform.util.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * 耗材价格查询服务层
 */
@Service
public class ConsumablesServiceImpl extends BaseService implements IConsumablesService {


    @Autowired
    private ISolrSearchService iSolrSearchService;

    /**
     * 条件查询，list页面
     * @param paramMap
     * @param request
     * @return
     */
    // @Cacheable(value = "SelectConsumablesByParam")缓存
    @SysLog("耗材价格查询")
    public ServerResponse<PageInfo> selectByParamMap(Map paramMap, HttpServletRequest request){
        if(StringUtil.isNotEmpty(StringUtil.valueOfString(paramMap.get("price")))){
            ServerResponse<PageInfo> response = MapperUtil.pageInfo(paramMap,consumablesMapper);
            if(response.isSuccess()){
                //查询大字段数据
                PageInfo pageInfo = response.getData();
                return SearchConsumablesUtil.selectBigText(pageInfo);
            }
        }else if(StringUtil.isEmpty(paramMap.get("productname")) && StringUtil.isEmpty(paramMap.get("sm"))
                        && StringUtil.isEmpty(paramMap.get("mb"))){
            ServerResponse<PageInfo> response = MapperUtil.pageInfo(paramMap,consumablesMapper);
            if(response.isSuccess()){
                //查询大字段数据
                PageInfo pageInfo = response.getData();
                return SearchConsumablesUtil.selectBigText(pageInfo);
            }
        }else{
            //纯solr查询
            try {
                return iSolrSearchService.sort(paramMap,request);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ServerResponse.createByErrorMessage(Const.Msg.SELECTERROR);
    }


    /**
     * 附件数据导入
     * @param fileUrl 附件访问地址
     * @return
     */
    @SysLog("耗材价格数据导入")
    public ServerResponse<String> importData(String fileUrl,HttpServletRequest request) {
        int resultNum = 0;
        if(StringUtil.isEmpty(fileUrl)){
            return ServerResponse.createBySuccessMessage(Const.Msg.PARAMTERERROR);
        }
        try{
            User u = (User)request.getSession().getAttribute(Const.CURRENT_USER);
            if(null == u){
                return ServerResponse.createBySuccessMessage(Const.Msg.USERNOLOGIN);
            }
            if(u.getRole() != Const.Role.ROLE_ADMIN){
                return ServerResponse.createBySuccessMessage(Const.Msg.NOACCESS);
            }
            String fileName = fileUrl/*fileUrl.substring(fileUrl.lastIndexOf("."))*/;//获取文件后缀名
            //判断格式
            if(!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")){
                return ServerResponse.createByErrorMessage(Const.Msg.FILEFORMATERROR);
            }
            //判断excel版本
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
            fileUrl = fileUrl.replaceAll("\\\\","/");
            URL url = new URL(PropertiesUtil.getProperty("filehttp")+fileUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3*1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            //得到输入流
            InputStream inputStream = conn.getInputStream();
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(inputStream);
            } else {
                wb = new XSSFWorkbook(inputStream);

            }
            //获取第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            Row row =  sheet.getRow(0);
            if(row.getPhysicalNumberOfCells() != 15){//最大列数
                return ServerResponse.createByErrorMessage("模板错误");
            }
            if(sheet == null){
                return ServerResponse.createByErrorMessage("没有数据");
            }
            int invalid = 0;
            for (int i = 1; i < rownum; i++) {
                try {
                    row = sheet.getRow(i);
                    if (row == null) {
                        continue;
                    }
                    if(invalid > 20){
                        return ServerResponse.createBySuccessMessage(Const.Msg.IMPORTSUCCESS);
                    }
                    Consumables consumables = new Consumables();//实体
                    consumables.setCatalogue(StringUtil.valueOfString(row.getCell(0)));//目录
                    String productName = StringUtil.valueOfString(row.getCell(1));
                    if(StringUtil.isEmpty(productName)){
                        invalid++;
                        continue;
                    }
                    consumables.setProductname(productName);//产品名称
                    /*consumables.setSpecifications(StringUtil.valueOfString(row.getCell(2)));//规格
                    consumables.setModel(StringUtil.valueOfString(row.getCell(3)));//型号*/
                    consumables.setUnit(StringUtil.valueOfString(row.getCell(4)));//计量单位
                    consumables.setPack(StringUtil.valueOfString(row.getCell(5)));//包装规格
                    consumables.setTexture(StringUtil.valueOfString(row.getCell(6)));//产品材质
                    consumables.setManufacture(StringUtil.valueOfString(row.getCell(7)));//生产厂家
                    consumables.setBidCompany(StringUtil.valueOfString(row.getCell(8)));//投标企业
                    consumables.setProduced(StringUtil.valueOfString(row.getCell(9)));//产地
                    consumables.setRegistrationNumber(StringUtil.valueOfString(row.getCell(10)));//注册证号
                    consumables.setRegistrationName(StringUtil.valueOfString(row.getCell(11)));//注册证名称
                    consumables.setPrice(NumberUtil.safeToDouble(row.getCell(12)));//价格
                    consumables.setDatahome(StringUtil.valueOfString(row.getCell(13)));//数据来源
                    if (null != row.getCell(14)) {
                        String datatime = StringUtil.valueOfString(row.getCell(14)).replaceAll("[.]", "-");//数据上报时间
                        if (StringUtil.isNotEmpty(datatime)) {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            consumables.setDatatime(sdf.parse(datatime));
                        }
                    }
                    if (consumablesMapper.insert(consumables) > 0) {
                        //查询最大ID值
                        Integer eid = consumablesMapper.selectMaxId();
                        if(eid != null && eid > 0){
                            //插入对应大字段
                            BigField bigField = new BigField();
                            bigField.setEid(eid);
                            bigField.setFieldname("model");//型号
                            bigField.setBigtext(StringUtil.valueOfString(row.getCell(3)));
                            bigFieldMapper.insert(bigField);
                            bigField = new BigField();
                            bigField.setEid(eid);
                            bigField.setFieldname("specifications");//规格
                            bigField.setBigtext(StringUtil.valueOfString(row.getCell(2)));
                            bigFieldMapper.insert(bigField);
                        }
                        resultNum++;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    continue;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ServerResponse.createBySuccessMessage(Const.Msg.IMPORTSUCCESS+resultNum+"条数据");
    }

    /**
     * 根据ID查询耗材价格详情
     * @param id
     * @param request
     * @return
     */
    @SysLog("根据ID查询耗材价格详情")
    public ServerResponse<Map> selectById(Integer id,HttpServletRequest request){
        Map resultMap = consumablesMapper.selectById(id);
        //查询型号规格大字段

        if(null != resultMap){
            return ServerResponse.createBySuccess(Const.Msg.SELECTSUCCESS,resultMap);
        }
        return ServerResponse.createBySuccessMessage(Const.Msg.SELECTERROR);
    }

}
